package com.ljh.onlinetest.controller.admin;

import com.github.pagehelper.PageInfo;
import com.ljh.onlinetest.base.BaseApiController;
import com.ljh.onlinetest.base.RestResponse;
import com.ljh.onlinetest.domain.Subject;
import com.ljh.onlinetest.domain.User;
import com.ljh.onlinetest.domain.UserEventLog;
import com.ljh.onlinetest.domain.enums.UserStatusEnum;
import com.ljh.onlinetest.domain.other.KeyValue;
import com.ljh.onlinetest.service.AuthenticationService;
import com.ljh.onlinetest.service.UserEventLogService;
import com.ljh.onlinetest.service.UserService;
import com.ljh.onlinetest.utils.DateTimeUtil;
import com.ljh.onlinetest.utils.PageInfoHelper;
import com.ljh.onlinetest.viewmodel.admin.user.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * @author ljh
 * @ClassName UserController.java
 * @createTime 2022年01月13日
 */
@RestController("AdminUserController")
@RequestMapping("/api/admin/user")
public class UserController extends BaseApiController {

    private final UserService userService;
    private final UserEventLogService userEventLogService;
    private final AuthenticationService authenticationService;

    @Autowired
    public UserController(UserService userService, UserEventLogService userEventLogService, AuthenticationService authenticationService) {
        this.userService = userService;
        this.userEventLogService = userEventLogService;
        this.authenticationService = authenticationService;
    }

    @PostMapping("/page/list")
    public RestResponse<PageInfo<UserResponseVM>> pageList(@RequestBody UserPageRequestVM model){
        PageInfo<User> pageInfo = userService.userPage(model);
        PageInfo<UserResponseVM> page = PageInfoHelper.copyMap(pageInfo, UserResponseVM::from);
        return RestResponse.ok(page);
    }

    @PostMapping("/select/{id}")
    public RestResponse<UserResponseVM> getUserById(@PathVariable Integer id){
        User user = userService.getUserById(id);
        UserResponseVM responseVM = UserResponseVM.from(user);
        return RestResponse.ok(responseVM);
    }

    @PostMapping("/selectByUserName")
    public RestResponse<List<KeyValue>> selectByUserName(@RequestBody String userName){
        List<KeyValue> keyValues = userService.selectByUserName(userName);
        return RestResponse.ok(keyValues);
    }

    @PostMapping("/edit")
    public RestResponse<User> edit(@RequestBody @Valid UserCreateVM model){
        User user = modelMapper.map(model, User.class);
        //create
        if (model.getId() == null) {
            User existingUser = userService.getUserByUserName(model.getUserName());
            if (existingUser != null) {
                return new RestResponse<>(2,"用户已存在");
            }
            if (StringUtils.isBlank(model.getPassword())){
                return new RestResponse<>(3,"密码不能为空");
            }
            String pwdEncode = authenticationService.pwdEncode(model.getPassword());
            user.setPassword(pwdEncode);
            user.setUserUuid(UUID.randomUUID().toString());
            user.setCreateTime(new Date());
            user.setLastActiveTime(new Date());
            user.setDeleted(false);
            userService.insertByFilter(user);
        } else {
            if (StringUtils.isBlank(model.getBirthDay())) {
                model.setBirthDay(null);
            }
            if (StringUtils.isNotBlank(model.getPassword())){
                String pwdEncode = authenticationService.pwdEncode(model.getPassword());
                user.setPassword(pwdEncode);
            }
            user.setModifyTime(new Date());
            userService.updateByIdFilter(user);
        }
        return RestResponse.ok(user);
    }

    @PostMapping("/delete/{id}")
    public RestResponse deleteById(@PathVariable Integer id){
        User user = userService.getUserById(id);
        user.setDeleted(true);
        userService.updateByIdFilter(user);
        return RestResponse.ok();
    }

    @PostMapping("/changeStatus/{id}")
    public RestResponse<Integer> updateStatus(@PathVariable Integer id){
        User user = userService.getUserById(id);
        UserStatusEnum userStatusEnum = UserStatusEnum.fromCode(user.getStatus());
        Integer newStatus = (userStatusEnum == UserStatusEnum.Enable ? UserStatusEnum.Disable.getCode() : UserStatusEnum.Enable.getCode());
        user.setStatus(newStatus);
        user.setModifyTime(new Date());
        userService.updateByIdFilter(user);
        return RestResponse.ok(newStatus);
    }


    @PostMapping("/event/page/list")
    public RestResponse<PageInfo<UserEventLogVM>> eventPage(@RequestBody UserEventPageRequestVM model){
        PageInfo<UserEventLog> pageInfo = userEventLogService.page(model);
        PageInfo<UserEventLogVM> vmPageInfo = PageInfoHelper.copyMap(pageInfo, e -> {
            UserEventLogVM vm = modelMapper.map(e, UserEventLogVM.class);
            vm.setCreateTime(DateTimeUtil.dateFormat(e.getCreateTime()));
            return vm;
        });
        return RestResponse.ok(vmPageInfo);
    }

    @PostMapping("/current")
    public RestResponse<UserResponseVM> current(){
        User currentUser = getCurrentUser();
        UserResponseVM userResponseVM = UserResponseVM.from(currentUser);
        return RestResponse.ok(userResponseVM);
    }

    @PostMapping("/update")
    public RestResponse update(@RequestBody @Valid UserUpdateVM model){
        User user = userService.selectById(getCurrentUser().getId());
        modelMapper.map(model,user);
        user.setModifyTime(new Date());
        userService.updateByIdFilter(user);
        return RestResponse.ok();
    }


}
